﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WeChartWorkRobot.Model;
using WeChartWorkRobot.Service;

namespace WeChartWorkRobot.Service
{
    public class MyHttpRequest
    {
        private Uri _url;

        private CookieContainer _cookieContainer;

        public MyHttpRequest(string url)
        {
            InitUrl(url);
        }

        public MyHttpRequest(string url, CookieContainer cookieContainer)
        {
            InitUrl(url);
            _cookieContainer = cookieContainer;
        }

        private void InitUrl(string url)
        {
            if (url.StartsWith("http"))
            {
                _url = new Uri(url);
            }
            else
            {
                throw new Exception("url格式不正确");
            }
        }

        public CookieContainer Login(string formString)
        {
            CookieContainer myCookieContainer = new CookieContainer();
            var bData = Encoding.UTF8.GetBytes(formString);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bData.Length;
            request.Accept = "application/json";
            request.CookieContainer = new CookieContainer();
            using (var writer = request.GetRequestStream())
            {
                writer.Write(bData, 0, bData.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string responseText = myreader.ReadToEnd();
                    LoginResult loginResult = JsonConvert.DeserializeObject<LoginResult>(responseText);
                    if (!loginResult.loginSucceeded)
                    {
                        throw new Exception("账号或密码错误");
                    }
                    foreach (Cookie ck in response.Cookies)
                    {
                        myCookieContainer.Add(ck);
                    }
                    return myCookieContainer;
                }
            }
        }

        /// <summary>
        /// GET方法
        /// </summary>
        /// <returns></returns>
        public T Get<T>()
        {
            // 创建一个HTTP请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "GET";
            request.Accept = "application/json";
            if (_cookieContainer != null)
            {
                request.CookieContainer = _cookieContainer;
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                var responseText = myreader.ReadToEnd();
                return JsonConvert.DeserializeObject<T>(responseText);
            }
        }

        public string Get()
        {
            // 创建一个HTTP请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "GET";
            request.Accept = "application/json";
            if (_cookieContainer != null)
            {
                request.CookieContainer = _cookieContainer;
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                var responseText = myreader.ReadToEnd();
                return responseText;
            }
        }

        /// <summary>
        /// POST方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="d"></param>
        /// <returns></returns>
        public T Post<T>(object d)
        {
            var data = JsonConvert.SerializeObject(d);
            LogHelper.Debug("param:" + data);
            var bData = Encoding.UTF8.GetBytes(data);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = bData.Length;
            request.Accept = "application/json";
            if (_cookieContainer != null)
            {
                request.CookieContainer = _cookieContainer;
            }

            using (var writer = request.GetRequestStream())
            {
                writer.Write(bData, 0, bData.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string responseText = myreader.ReadToEnd();
                    LogHelper.Debug("result" + responseText);
                    return ConvertResult<T>(responseText);
                }
            }
        }

        /// <summary>
        /// PostForm方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="formString"></param>
        /// <returns></returns>
        public T PostForm<T>(string formString)
        {
            var bData = Encoding.UTF8.GetBytes(formString);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bData.Length;
            request.Accept = "application/json";
            if (_cookieContainer != null)
            {
                request.CookieContainer = _cookieContainer;
            }
            using (var writer = request.GetRequestStream())
            {
                writer.Write(bData, 0, bData.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string responseText = myreader.ReadToEnd();
                    return ConvertResult<T>(responseText);
                }
            }
        }

        private T ConvertResult<T>(string responseText)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(responseText);
            }
            catch
            {
                throw new Exception($"接口调用失败:\r\n异常信息:{responseText}");
            }
        }
    }
}
